<?php
class User extends Controller {

	function User(){
		parent::Controller();	
		$this->load->model("M_Common","common");
		$this->load->model("M_Users","user");
		$this->load->library('interface_bill');
	}
	function index(){
		$data["title"] = "InvoiceSystem";
		$this->load->view('welcome_message', $data);
	}	
	function introducere(){
		switch ($this->uri->segment(3)){
			case 'factura' :
			//introducere factura -----
			//-------------------------
				$data['title'] = 'Introducere factura';
				$this->load->view('user/introducere/factura',$data);
			
			//-------------------------
				break;
				
		} //end switch
	} //end function
	
	function nomenclatoare(){
		switch ($this->uri->segment(3)){
			case 'clienti' :
			//administrare clienti ----
			//-------------------------
				$data['title'] = 'Administrare clienti';
				$this->load->view('user/nomenclatoare/clienti',$data);
			
			//-------------------------
				break;
			case 'produse':
			//administrare produse -----
			//--------------------------
				$data['title'] = 'Administrare produse';
				$this->load->view('user/nomenclatoare/produse',$data);
			
			//--------------------------
				break;	
				
		} //end switch
	} //end function	
	
	function rapoarte(){
		switch ($this->uri->segment(3)){
			case 'facturi' :
			//raport facturi ----------
			//-------------------------
				switch($this->uri->segment(4)){
					case 'emise' :
					//raport facturi incasate -
					//-------------------------
						$data['title'] = 'Raport facturi emise';
						$this->load->view('user/rapoarte/facturi/emise',$data);					
					//-------------------------					
						break;			
					case 'anulate' :
					//raport facturi anulate --
					//-------------------------
						$data['title'] = 'Raport facturi anulate';
						$this->load->view('user/rapoarte/facturi/anulate',$data);					
					//-------------------------					
						break;	
					case 'neincasate' :
					//raport facturi neincasate --
					//----------------------------
						$data['title'] = 'Raport facturi neincasate';
						$this->load->view('user/rapoarte/facturi/neincasate',$data);					
					//----------------------------					
						break;		
					case 'scadente' :
					//raport facturi scadente --
					//----------------------------
						$data['title'] = 'Raport facturi scadente';
						$this->load->view('user/rapoarte/facturi/scadente',$data);					
					//----------------------------					
						break;																											
				} //end switch 
			
			//-------------------------
				break;
			case 'incasari':
			//raport incasari ----------
				switch($this->uri->segment(4)){
					case 'anulate' :
					//raport incasari anulate -
					//-------------------------
						$data['title'] = 'Raport incasari anulate';
						$this->load->view('user/rapoarte/incasari/anulate',$data);					
					//-------------------------					
						break;												
				} //end switch 
			//--------------------------
				break;	
				
		} //end switch
	} //end function	
	
	function contabilitate(){				
		switch ($this->uri->segment(3)){
			case 'jurnaltva' :
			//raport jurnal tva -------
			//-------------------------
				$isgrid = $this->uri->segment(4);
				
				if(isset($isgrid) && !empty($isgrid) && ($isgrid == 'getTable')){
					/*
					 * put this AJAX safe request check in every CI function called by AJAX 
					 * 
					 */
					//verify AJAX request[saferequest = true]
					$request		= false;
					$saferequest 	= $this->input->post('saferequest');
							
					$request = (!empty($saferequest) && ($saferequest == true)) ? true : false; 
					$url = $this->config->config['base_url']."user/contabilitate/jurnaltva/getTable/";
					$this->ajax_request->_check_request($url,$request);
					//--------------------------------------------------------------------------------	
										
					$s_limit 			= $this->input->post("start");
					$e_limit 			= $this->input->post("limit");
					$dir 				= $this->input->post("dir");
					$sort 				= $this->input->post("sort");
					$moneda				= $this->input->post("moneda");
					$ds					= $this->input->post("dela");
					$de					= $this->input->post("panala");
					
					//Data source table name with uppercase
					echo json_encode($this->common->mSelectTVAJournal($moneda,$ds,$de,$s_limit,$e_limit,$sort,$dir));								
				}else {
					$data['title'] = 'Raport jurnal TVA';
					$this->load->view('user/contabilitate/jurnal-tva',$data);
				}
			//-------------------------
				break;
			case 'borderoucasa':
			//raport borderou casa -----
			//--------------------------
				$isgrid = $this->uri->segment(4);
				
				if(isset($isgrid) && !empty($isgrid) && ($isgrid == 'getTable')){
					/*
					 * put this AJAX safe request check in every CI function called by AJAX 
					 * 
					 */
					//verify AJAX request[saferequest = true]
					$request		= false;
					$saferequest 	= $this->input->post('saferequest');
							
					$request = (!empty($saferequest) && ($saferequest == true)) ? true : false; 
					$url = $this->config->config['base_url']."user/contabilitate/borderoucasa/getTable/";
					$this->ajax_request->_check_request($url,$request);
					//--------------------------------------------------------------------------------	
										
					$s_limit 			= $this->input->post("start");
					$e_limit 			= $this->input->post("limit");
					$dir 				= $this->input->post("dir");
					$sort 				= $this->input->post("sort");
					$moneda				= $this->input->post("moneda");
					$ds					= $this->input->post("dela");
					$de					= $this->input->post("panala");
					
					//Data source table name with uppercase
					echo json_encode($this->common->mSelectHomeBorderou($moneda,$ds,$de,$s_limit,$e_limit,$sort,$dir));								
				}else {
					$data['title'] = 'Raport borderou de casa';
					$this->load->view('user/contabilitate/borderou-casa',$data);
				}			
			//--------------------------
				break;	
				
		} //end switch
	} //end function	
	
	function setari(){
		switch ($this->uri->segment(3)){
			case 'generale':
			//setari generale ----------
			//--------------------------
				$data['title'] = 'Setari generale';
				$this->load->view('user/setari/generale',$data);
			
			//--------------------------
				break;	
				
		} //end switch
	} //end function	
	function plati(){
		switch ($this->uri->segment(3)){
			case 'platiefectuate':
			//plati efectuate ----------
			//--------------------------
				$data['title'] = 'Plati efectuate';
				$this->load->view('user/plati/plati-efectuate',$data);
			
			//--------------------------
				break;	
				
		} //end switch
	} //end function			
	function functionalitati(){
				/*
				 * put this AJAX safe request check in every CI function called by AJAX 
				 * 
				 */
				//verify AJAX request[saferequest = true]
				$request= false;
				$saferequest = $this->input->post('saferequest');
				
				$request = (!empty($saferequest) && ($saferequest == true)) ? true : false; 
				$url = $this->config->config['base_url']."user/functionalitati/";
				$this->ajax_request->_check_request($url,$request);
				//--------------------------------------------------------------------------------	
						
		switch ($this->uri->segment(3)){
			case 'excel':
			//export excel ---
			//-------------------------			
				$this->load->plugin('to_excel');			
				$table= $this->input->post('table');
				$filename= $this->input->post('filename');
				$qsearch			= json_decode($this->input->post("fields"));
				$s_limit 			= $this->input->post("start");
				$e_limit 			= $this->input->post("limit");
				$dir 				= $this->input->post("dir");
				$sort 				= $this->input->post("sort");
				$qsearchlikestring	= $this->input->post("query");
							
				
				//header("Content-Type: application/vnd.ms-excel");
				//header("Content-Disposition: attachment; filename=$filename.xls");
				header("Content-type: application/octet-stream");
				header("Content-Disposition: attachment; filename=$filename.xls;");
				header("Content-Type: application/ms-excel");
				header("Pragma: no-cache");	
				header("Expires: 0");			
				
				switch ($table){
					case 'facturi_scadente':				
						to_excel($this->common->mSelectNotPayedBills($excel=true,$table,$s_limit,$e_limit,$sort,$dir,$qsearch,$qsearchlikestring),$filename);
					break;
					case 'facturi_neincasate':
						to_excel($this->common->mSelectNotPayedBills($excel=true,$table,$s_limit,$e_limit,$sort,$dir,$qsearch,$qsearchlikestring),$filename);
					break;					
					case 'plati_efectuate':
						to_excel($this->common->mSelectPaysXLS($excel=true,$table,$s_limit,$e_limit,$sort,$dir,$qsearch,$qsearchlikestring),$filename);					
					break;					
				}
	
			//-------------------------
				break;
			case 'salvare' :
			//salvare factura ---
			//-------------------------
				$dataDS = array();
				$dataDS = $_POST;
				
				//sending action type parameter ['save' or 'view' or 'preview'] corresponding to user action ['save bill' or 'view db bill' or 'preview interface bill']
				$data = $this->interface_bill->build($dataDS,'save');

				$response = $this->common->mInsertBill($data['bill'],$dataDS['articole'],$data['tva']);
				
				if(($response[0] == true) && ($response[1] == true) && ($response[2] == true) && ($response[3] == true)){
					echo json_encode(array(
					        'success'=> true,
					        'code' => 1			//success
					    ));					
				} elseif($response[0] == false){
						echo json_encode(array(
					        'success'=> true,
					        'code' => 2			//transactie nereusita
					    ));					
				} elseif($response[1] == false){
						echo json_encode(array(
					        'success'=> true,
					        'code' => 3			//introducere factura nereusita
					    ));					
				} elseif($response[2] == false){
						echo json_encode(array(
					        'success'=> true,
					        'code' => 4			//introducere articole nereusita
					    ));	
				} elseif($response[3] == false){
						echo json_encode(array(
					        'success'=> true,
					        'code' => 5			//actualizare counter nereusita
					    ));												
			    }else{
					echo json_encode(array(
					        'success'=> true,
					        'code' => 0
					    ));  
			    }				
			//-------------------------
				break;
			case 'anulare_incasare' :
			//anulare factura ---
			//-------------------------	
				$data = array();
				$dataDS = $_POST;		
				$commonData=array(
									'saferequest' 	=> $this->input->post('saferequest'),
									'table' 		=> $this->input->post('table'),
									'cyDep'			=> $this->input->post('cyDep'),
									'data_emiterii'	=> $this->input->post('data_emiterii')
				);				
				//excluding ajax call variables 				
				$neededData = array_diff_assoc($dataDS,$commonData);
		
				foreach($neededData as $key => $value){
				      	$data[$key]=$value;
				}
				$response = $this->common->mInsertCanceledPay($data);	
				if(($response[0] == true) && ($response[1] == true)){
					echo json_encode(array(
					        'success'=> true,
					        'code' => 1			//success
					    ));					
				} elseif($response[0] == false){
						echo json_encode(array(
					        'success'=> true,
					        'code' => 2			//transactie nereusita
					    ));					
				} elseif($response[1] == false){
						echo json_encode(array(
					        'success'=> true,
					        'code' => 3			//stergere incasari nereusita
					    ));					
				}										
			//-------------------------
				break;				
			case 'anulare' :
			//anulare factura ---
			//-------------------------
				$data = array();
				$dataDS = $_POST;		
				$commonData=array(
									'saferequest' 	=> $this->input->post('saferequest'),
									'table' 		=> $this->input->post('table'),
									'cyDep'			=> $this->input->post('cyDep')	
				);	
				//excluding ajax call variables 				
				$neededData = array_diff_assoc($dataDS,$commonData);
		
				foreach($neededData as $key => $value){
				      	$data[$key]=$value;
				}
				
				$response = $this->common->mInsertCanceledBill($data);	
				
				if(($response[0] == true) && ($response[1] == true) && ($response[2] == true) && ($response[3] == true)){
					echo json_encode(array(
					        'success'=> true,
					        'code' => 1			//success
					    ));					
				} elseif($response[0] == false){
						echo json_encode(array(
					        'success'=> true,
					        'code' => 2			//transactie nereusita
					    ));					
				} elseif($response[1] == false){
						echo json_encode(array(
					        'success'=> true,
					        'code' => 3			//stergere incasari nereusita
					    ));					
				} elseif($response[2] == false){
						echo json_encode(array(
					        'success'=> true,
					        'code' => 4			//stergere articole nereusita
					    ));	
				} elseif($response[3] == false){
						echo json_encode(array(
					        'success'=> true,
					        'code' => 5			//stergere factura nereusita
					    ));												
			    }else{
					echo json_encode(array(
					        'success'=> true,
					        'code' => 0
					    ));  
			    }								
			//-------------------------
				break;
			case 'verificaIncasari' :
			//verifica incasari/factura ---
			//-------------------------
				$id = $this->input->post('ID');
				$response = $this->common->mSelectNumRows('incasari','FK_FACTURI',$id);
				
				if($response > 0){
					echo json_encode(array(
					        'success'=> true,
					        'code' => $response			//success
					    ));						
				}else {
					echo json_encode(array(
					        'success'=> true,
					        'code' => 0			//success
					    ));						
				}	
							
			//-------------------------
				break;		
			case 'verificaClientEmail' :
			//verifica client email ---
			//-------------------------
				$id = $this->input->post('ID');
				$response = $this->common->mSelectClientEmail($id);
				
				if(isset($response) && !empty($response)){
					echo json_encode(array(
					        'success'=> true,
					        'code' => $response			//client with mail
					    ));						
				}else {
					echo json_encode(array(
					        'success'=> true,
					        'code' => 0					//client without e-mail
					    ));						
				}	
							
			//-------------------------
				break;				
			case 'incasare' :
				$dataDS = array();
				$dataDS = $_POST;
				
				$commonData=array(
									'saferequest' 	=> $this->input->post('saferequest'),
									'table' 		=> $this->input->post('table'),
									'cyDep'			=> $this->input->post('cyDep'),
									'numar'			=> $this->input->post('numar')		
				);
		
				//excluding ajax call variables 				
				$neededData = array_diff_assoc($_POST,$commonData);
		
				foreach($neededData as $key => $value){
				      	$data[$key]=$value;
				}							
				
				$response = $this->common->mInsertPay($data);
				
				if(($response[0] == true) && ($response[1] == true) && ($response[2] == true)){
					if(isset($response[3]) && !empty($response[3])){
						echo json_encode(array(
						        'success'	=> true,
						        'code' 		=> 1,
								'id'		=> $response[3]		//success
						    ));						
					}
					else {
						echo json_encode(array(
						        'success'	=> true,
						        'code' 		=> 1,				//success
						    ));							
					}				
				} elseif($response[0] == false){
						echo json_encode(array(
					        'success'=> true,
					        'code' => 2							//transactie nereusita
					    ));					
				} elseif($response[1] == false){
						echo json_encode(array(
					        'success'=> true,
					        'code' => 3							//introducere incasare nereusita
					    ));					
				} elseif($response[2] == false){
						echo json_encode(array(
					        'success'=> true,
					        'code' => 4							//actualizare counter nereusita
					    ));	
				} else{
					echo json_encode(array(
					        'success'=> true,
					        'code' => 0
					    ));  
			    }
			//-------------------------	
			break;				
			case 'chitanta' :
				$sess 		= $this->session->userdata('us_');
				$cId 		= $sess['us_C'];
				$user 		= $sess['us_N'];				
				
				$rowPay 	= $this->common->mSelectWhere('incasari',$this->input->post('ID'));
				$rowBill 	= $this->common->mSelectWhere('facturi',$rowPay[0]['FK_FACTURI']);
				$rowCode	= $this->common->mSelectBillCode($cId);
				
				$company 	= $this->common->mSelectCompany($cId);
				$client		= $this->common->mSelectWhere('clienti',$rowBill[0]['FK_CLIENTI']);
				$moneda		= $this->common->mSelectReferenceById($rowBill[0]['moneda']);
				$judet_cl	= $this->common->mSelectReferenceById($client[0]['judet']);
				$nr_factura = $rowBill[0]['numar'];
				
				//transforming to characters
				//-----------------------------------------------------------------------------------------------------------
				switch ($moneda->value) {
					case 'RON':
						$sign1 = 'leu';
						$sign2 = 'lei';
						$sign11 = 'ban';
						$sign12 = 'bani';
						break;
					case 'EUR':
						$sign1 = 'euro';
						$sign2 = 'euro';
						$sign11 = 'centi';
						$sign12 = 'centi';
						break;
				}					
				$temp=explode("." , $rowPay[0]['valoarea']);

				if($temp[0]=="1")  {
					$n2c = render_number($temp[0]).$sign1;
				}else {
					$n2c = render_number($temp[0]).$sign2;
				}
				   
				if($temp[1] && $temp[1]!="00" && count($temp[1])<3 ){
					if($temp[1]=="01")  {
						$n2c .= "si".render_number($temp[1]).$sign11;	
					}else {
						$n2c .= "si".render_number($temp[1]).$sign12;		
					}
				}else{}	
				//-----------------------------------------------------------------------------------------------------------		
				$dataDS		= array(
									'compania'	=> $company,
									'client'	=> $client,
									'judet_cl'	=> $judet_cl->value,
									'casier'	=> $user,
									'moneda'	=> $moneda->value,
									'incasare'	=> $rowPay,
									'caractere'	=> $n2c,
									'nr_factura'=> $nr_factura,
									'seria'		=> $rowCode->seria	
				);
				
				$header = '
				        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
						<html>
						<head>
						<base href="'. $this->config->config['base_url'] .'" />
						<link rel="stylesheet" type="text/css" href="resources/css/app/chitanta.css" />
						<title>Tiparire chitanta</title>
						<style>
							body, table {
								font-family:Arial, Helvetica, sans-serif;
								font-size:11px;
							}
							.furnizorDescriere {
								font-family:Arial, Helvetica, sans-serif;
								font-size:11px;
								position:relative;
								margin-right:5px;
							}
							.chitantaItem {
								border-bottom:1px dotted #000000;
							}
							.titluFactura {
								font-family:Verdana, Arial, Helvetica, sans-serif;
								font-size:24px;
								font-weight:bold;
								
							}
						</style>						
						</head>		
						<body>
				';		
				$content = '
					<div style="border:1px solid #000000; padding-left:2px;">
							  <table width="100%" border="0" cellpadding="0" cellspacing="0">
					            <tr>
					              <td width="50%" rowspan="2" valign="top">
								  
                                      <div style="font-size:11px;" class="furnizorDescriere">
                                      
                                        <table width="100%" border="0" cellspacing="0" cellpadding="2px">
                                          <tr>
                                            <td width="32%" height="8" valign="top">
                                              <div align="left">Furnizor:</div></td>
                                            <td width="68%" valign="top"><div align="left">'. $dataDS['compania'][0]['nume'] .'</div></td>
                                          </tr>
                                          <tr>
                                            <td width="32%" height="8" valign="top"><div align="left">C.I.F.:</div></td>
                                            <td width="68%" valign="top"><div align="left">'. $dataDS['compania'][0]['cui'] .'</div></td>
                                          </tr>
                                          <tr>
                                            <td width="32%" height="8" valign="top"><div align="left">Nr.reg. com:</div></td>
                                            <td width="68%" valign="top"><div align="left">'. $dataDS['compania'][0]['nr_reg'] .'</div></td>
                                          </tr>
                                        </table>
                                        
                                      </div>								  
								  <div class="furnizorDescriere">
					                  <table width="100%" border="0" cellspacing="0" cellpadding="2px">
					                    <tr>
					                      <td width="32%" height="8" valign="top"><div align="left">Domiciliul fiscal :</div></td>
					                        <td width="68%" height="8" valign="top"><div align="left">'. $dataDS['compania'][0]['adresa'] .'</div></td>
					                      </tr>
					                    <tr>
					                      <td width="32%" height="8" valign="top"><div align="left"><b>IBAN RON:</b></div></td>
					                        <td width="68%" height="8" valign="top"><div align="left">'. $dataDS['compania'][0]['iban1'] .'</div></td>
					                      </tr>
					                    <tr>
					                      <td width="32%" height="8" valign="top"><div align="left">Banca:</div></td>
					                        <td width="68%" height="8" valign="top"><div align="left">'. $dataDS['compania'][0]['banca1'] .'</div></td>
					                      </tr>';
										  if (!empty( $dataDS['compania'][0]['banca2']) && !empty($dataDS['compania'][0]['iban2'])) {                     
					 		$content .= '<tr>
					    					<td width="32%" height="8" valign="top"><div align="left"><b>IBAN EUR:</b></div></td>
					                        <td width="68%" height="8" valign="top"><div align="left">'. $dataDS['compania'][0]['iban2'] .'</div></td>
					                      </tr>
					                    <tr>
					                      <td width="32%" height="8" valign="top"><div align="left">Banca:</div></td>
					                        <td width="68%" height="8" valign="top"><div align="left">'. $dataDS['compania'][0]['banca2'] .'</div></td>
					                      </tr>';
										                      
					                      }
					       	$content .= '</table>
					                </div></td>
					              <td height="72" valign="top">&nbsp;</td>
					              <td width="33%" height="72" valign="top"><table width="100%" height="19" border="0" cellpadding="0" cellspacing="0">
					                  <tr>
					                    <td height="19" valign="top">
										<div align="center">
					                        <div align="right" style="padding-right:10px;">&nbsp;</div>
					                    </div></td>
					                  </tr>
					              </table></td>
					            </tr>
					            <tr>
					              <td height="72" colspan="2" valign="bottom">
								  <div align="left" class="titluFactura" style="padding-left:80px;">
					                CHITAN&#354;&#258;
					              </div>
								  
					                  <table width="100%" height="57" border="0" cellpadding="0" cellspacing="0">
					                    <tr>
					                      <td width="22%" height="30" valign="bottom" >&nbsp;</td>
					                      <td width="19%" valign="bottom" ><div align="left">Nr.</div></td>
					                      <td width="59%" height="30" valign="bottom" ><div align="left">'. $dataDS['incasare'][0]['nr_chit'] .'</div></td>
					                    </tr>
					                    <tr>
					                      <td height="30" valign="bottom" >&nbsp;</td>
					                      <td height="30" valign="bottom" ><div align="left">Seria</div></td>
					                      <td height="30" valign="bottom" ><div align="left">'. $dataDS['seria'] .'</div></td>
					                    </tr>
					                    <tr>
					                      <td height="20" valign="bottom" >&nbsp;</td>
					                      <td height="20" valign="bottom" ><div align="left">Data:</div></td>
					                      <td height="9" valign="bottom" ><div align="left">'.  DateConvertFromMySql($dataDS['incasare'][0]['data'],'d-m-Y') .'</div></td>
					                    </tr>
					                </table>
									
									</td>
					              </tr>
					            <tr>
					              <td colspan="3" valign="bottom"><table width="100%" border="0" cellpadding="0" cellspacing="0">
					                  <tr>
					                    <td width="15%" height="22" valign="middle"><div align="left">Am primit de la: </div></td>
					                    <td height="22" colspan="2" valign="middle"><div align="left" class="chitantaItem">'. $dataDS['client'][0]['nume'] .'</div></td>
					                  </tr>
					                  <tr>
					                    <td height="22" valign="middle" ><div align="left">Adresa:</div></td>
					                    <td height="22" colspan="2" valign="middle" ><div align="right" >
					                        <div align="left" class="chitantaItem">'. $dataDS['client'][0]['adresa'] .', Jude&#355;ul '. $dataDS['judet_cl'] .'</div>
					                    </div></td>
					                  </tr>
					                  <tr>
					                    <td height="22" valign="middle" ><div align="left">Suma de: </div></td>
					                    <td width="21%" height="22" valign="middle" ><div align="left" class="chitantaItem">'. $dataDS['incasare'][0]['valoarea'] .'</div></td>
					                    <td width="64%" height="22" valign="middle" ><div class="chitantaItem">&nbsp;</div></td>
					                  </tr>
					                  <tr>
					                    <td height="22" valign="middle" ><div align="left">adic&#259;:</div></td>
					                    <td height="22" colspan="2" valign="middle" ><div align="left" class="chitantaItem">'.$dataDS['caractere'].'</div></td>
					                  </tr>
					                  <tr>
					                    <td height="22" valign="middle" ><div align="left">reprezent&acirc;nd:</div></td>
					                    <td height="22" colspan="2" valign="middle" ><div align="left" class="chitantaItem">Contravaloare factura serie '. $dataDS['seria'] .', numar '. $dataDS['nr_factura'] .'</div></td>
					                  </tr>
					                  <tr>
					                    <td height="22" valign="middle" >&nbsp;</td>
					                    <td height="25" colspan="2" valign="middle" ><div align="right" style="margin-right:100px;">Casier, </div></td>
					                  </tr>
					              </table></td>
					            </tr>
					          </table>
							</div>				
				';		
				$footer = '
				</body>
				</html>
				';		
				$separator = '
				<div style="height:50px; padding-top:40px;">
					<hr  style="border:0px; background-color:#000000; height:1px;"/>
				</div>
				';				
				echo $header.$content.$separator.$content.$footer;					
			//-------------------------	
			break;				
			case 'pdf' :
			//trimitere factura pdf ---
			//-------------------------

				$dataDS = '';
				$ID = $this->input->post('ID');
				
				if (isset($ID) && !empty($ID)){
					$dataDS = json_decode($this->common->mSelectBillWhere($ID),true);
				} else {
					$dataDS = json_decode($this->input->post('DATA_DS'),true);
				}
				
				$data['bill'] = $this->interface_bill->build($dataDS,'view');			
				
				$html = $this->load->view('user/functionalitati/pdf', $data, TRUE);
				pdf_create($html, $data['bill']['numar'], false);
			
				$this->email->from('contact@iello.ro');
				$this->email->to($data['bill']['client'][0]['email']);		
				//$this->email->to('contact@iello.ro');	
				//$this->email->cc('transpetcompany@gmail.com');		
				
				$this->email->subject($data['bill']['compania'][0]['nume'] .'; Factura nr. '. $data['bill']['numar'] .' ['. $data['bill']['client'][0]['nume'] .']');
				$this->email->message('
				<table border=0 cellpadding=5 cellspacing=0 style=border-collapse: collapse bordercolor=#e8e8e8><tr><td>
					<font size="2" face="Verdana">Data emiterii: '. $data['bill']['data_emiterii'] .'</font><br />
					<font size="2" face="Verdana">Data scadentei: '. $data['bill']['data_scadentei'] .'</font><br />
					<font size="2" face="Verdana">Detalii: '. $data['bill']['detalii'] .'</font>
				</td></tr></table>
						
				');
				$this->email->attach('./tmp/pdf/factura_'. $data['bill']['numar'].'.pdf');			

				if($this->email->send()){
					echo json_encode(array(
					        'success'=> true,
					        'code' => 1			//success
					    ));		
					$this->clearTempDataPDF();									
				} else{
					echo json_encode(array(
					        'success'=> true,
					        'code' => 0
					    ));
					$this->clearTempDataPDF();		  					
				}
				//-------------------------
				break;
				
			case 'previzualizare':
			//previzualizare factura ---
			//--------------------------
				$dataDS = '';
				$ID = $this->input->post('ID');
				if (isset($ID) && !empty($ID)){
					$action = "view";
					$dataDS = json_decode($this->common->mSelectBillWhere($ID),true);
				} else {
					$action = "preview";
					$dataDS = json_decode($this->input->post('DATA_DS'),true);
				}
				
				$data['bill'] = $this->interface_bill->build($dataDS,$action);			

//				echo "<pre>";
//				print_r($data['bill']);
//				echo "</pre>"; die();

				$header = '
				        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
						<html>
						<head>
						<base href="'. $this->config->config['base_url'] .'" />
						<link rel="stylesheet" type="text/css" href="resources/css/app/print.css" />
						<title>Previzualizare factura</title>
						</head>		
						<body>
				';
				$content = '
					<table width="100%" border="0" cellpadding="0" cellspacing="0">
					  <tr>
					    <td><table width="96%" border="0" cellspacing="0" cellpadding="0">
					      <tr>
					        <td width="100%" height="177" valign="top">
								<table width="100%" border="0" cellspacing="5" cellpadding="4" id="header">
					          		<tr>
					            		<td width="45%" valign="top">
											<table width="100%" border="0" cellspacing="0" cellpadding="0">
					      						<tr>
					        						<td height="17" colspan="2"><div align="left" class="titluFactura">FACTUR&#258;</div></td>
					      						</tr>
					      						<tr>
					        						<td width="40%" height="17">      
														<div align="left" class="seriaNumar"> Seria: '. $data['bill']['seria'] .'</div>
													</td>
					        						<td width="60%"><div align="left" class="seriaNumar"> NR: '. $data['bill']['numar'] .'</div></td>
					     						</tr>
					      						<tr>
					        						<td height="17" colspan="2">&nbsp;</td>
					      						</tr>
					    					</table>
					                          <table width="100%" border="0" cellspacing="0" cellpadding="0" style="font-size:11px;">
					                            <tr>
					                              <td width="40%"><div align="left">Data:</div></td>
					                              <td width="60%"><div align="left">'. DateConvertFromMySql($data['bill']['data'],'d-m-Y') .'</div></td>
					                            </tr>
					                          </table>
					          					<br />
					                          <table width="100%" border="0" cellspacing="0" cellpadding="0" style="font-size:11px;">
					                            <tr>
					                              <td width="40%"><div align="left">Cota T.V.A.</div></td>
					                              <td width="60%"><div align="left">'. $data['bill']['tva'] .' %</div></td>
					                            </tr>
					                            <tr>
					                              <td width="40%"><div align="left"><b>Data scadentei:</b></div></td>
					                              <td width="60%"><div align="left">'. DateConvertFromMySql($data['bill']['data_scadentei'],'d-m-Y') .'</div></td>
					                            </tr>
					                          </table>
					                  </td>	
					                  <td width="55%" valign="top">
					            
					                    <div align="right">
					                          <table width="100%" border="0" cellspacing="0" cellpadding="2" id="furnizorDescriere">
					                            <tr>
					                              <td width="22%" height="8" valign="top"><div align="left">Furnizor:</div></td>
					                              <td width="78%" height="8" valign="top"><div align="left">'. $data['bill']['compania'][0]['nume'] .'</div></td>
					                            </tr>
					                            <tr>
					                              <td width="22%" height="3" valign="top"><div align="left">C.I.F.:</div></td>
					                              <td width="78%" height="3" valign="top"><div align="left">'.  $data['bill']['compania'][0]['cui'] .'</div></td>
					                            </tr>
					                            <tr>
					                              <td width="22%" height="8" valign="top"><div align="left">Capital social:</div></td>
					                              <td width="78%" height="8" valign="top"><div align="left">'. $data['bill']['compania'][0]['capital'] .'</div></td>
					                            </tr>
					                            <tr>
					                              <td width="22%" height="8" valign="top"><div align="left">Nr.R.C/Aut.:</div></td>
					                              <td width="78%" height="8" valign="top"><div align="left">'. $data['bill']['compania'][0]['nr_reg'] .'</div></td>
					                            </tr>
					                            <tr>
					                              <td width="22%" height="8" valign="top"><div align="left">Domiciliul fiscal:</div></td>
					                              <td width="78%" height="8" valign="top"><div align="left">'. $data['bill']['compania'][0]['adresa'] .'</div></td>
					                            </tr>
					                            <tr>
					                              <td width="22%" height="8" valign="top"><div align="left"><b>IBAN:</b></div></td>
					                              <td width="78%" height="8" valign="top"><div align="left">'. $data['bill']['compania'][0]['iban1'] .'</div></td>
					                            </tr>
					                            <tr>
					                              <td width="22%" height="8" valign="top"><div align="left">Banca:</div></td>
					                              <td width="78%" height="8" valign="top"><div align="left">'. $data['bill']['compania'][0]['banca1'] .'</div></td>
					                            </tr>';
					              if(isset($data['bill']['compania'][0]['banca2']) && !empty($data['bill']['compania'][0]['banca2'])){
					                $content .= '<tr>
					                              <td width="22%" height="8" valign="top"><div align="left"><b>IBAN:</b></div></td>
					                              <td width="78%" height="8" valign="top"><div align="left">'. $data['bill']['compania'][0]['iban2'] .'</div></td>
					                            </tr>
					                            <tr>
					                              <td width="22%" height="8" valign="top"><div align="left">Banca:</div></td>
					                              <td width="78%" height="8" valign="top"><div align="left">'. $data['bill']['compania'][0]['banca2'] .'</div></td>
					                            </tr>';
					              }            
					                $content .= '</table>
					                        </div>            
					            	</td>
					            </tr>
					        </table>
					          <table width="100%" border="0" cellspacing="0" cellpadding="4" id="header-child">
					            <tr>
					              <td>
					                <table width="100%" border="0" cellspacing="0" cellpadding="0" id="clientDescriere">
					                  <tr>
					                    <td width="9%" height="17" valign="top"><div align="left">Cumparator:</div></td>
					                    <td width="91%" valign="top"><div align="left"> '. $data['bill']['client'][0]['nume'] .'</div></td>
					                  </tr>
					                  <tr>
					                    <td height="17"><div align="left">Nr.R.C/Aut.: </div></td>
					                    <td height="17"><div align="left">'. $data['bill']['client'][0]['nr_reg'] .'</div></td>
					                  </tr>
					                  <tr>
					                    <td height="17"><div align="left">C.I.F: </div></td>
					                    <td height="17"><div align="left">'. $data['bill']['client'][0]['cui'] .'</div></td>
					                  </tr>
					                  <tr>
					                    <td height="17" valign="top"><div align="left">Adresa:</div></td>
					                    <td height="17" valign="top"><div align="left">'. $data['bill']['client'][0]['adresa'] .'</div></td>
					                  </tr>
					
					                  <tr>
					                    <td height="17"><div align="left">Contul: </div></td>
					                    <td height="17"><div align="left">'. $data['bill']['client'][0]['cont'] .'</div></td>
					                  </tr>
					                  <tr>
					                    <td height="17"><div align="left">Banca: </div></td>
					                    <td height="17"><div align="left">'. $data['bill']['client'][0]['banca'] .'</div></td>
					                  </tr>
					                </table>
					              </div></td>
					            </tr>
					          </table>
							</td>
					        </tr>
					      <tr>
					        <td valign="top">
							<table width="100%" border="0" cellspacing="0" cellpadding="0" id="factura">
					          <tr>
					            <td width="3%" height="40" valign="middle" bgcolor="#FFFFFF"><div align="center">Nr. <br />
					              Crt </div></td>
					            <td width="42%"  height="40" valign="middle" bgcolor="#FFFFFF"><div align="center">Denumirea produselor sau a serviciilor </div></td>
					            <td width="7%"  height="40" valign="middle" bgcolor="#FFFFFF"><div align="center">U.M.</div></td>
					            <td width="12%"  height="40" valign="middle" bgcolor="#FFFFFF"><div align="center">Cantitatea</div></td>
					            <td width="12%"  height="40" valign="middle" bgcolor="#FFFFFF"><div align="center">Pretul unitar<br />
					              (f&#259;r&#259; TVA)<br />
					            - '. $data['bill']['moneda'] .' - </div></td>
					            <td width="12%"  height="40" valign="middle" bgcolor="#FFFFFF"><div align="center">Valoarea<br />
					            - '. $data['bill']['moneda'] .' -</div></td>
					            <td width="12%"  height="40" valign="middle" bgcolor="#FFFFFF"><div align="center">TVA<br />
					            - '. $data['bill']['moneda'] .' -</div></td>
					          </tr>
					          <tr>
					            <td width="3%" height="5" valign="middle" bgcolor="#FFFFFF"><div align="center">0</div></td>
					            <td width="42%"  height="5" valign="middle" bgcolor="#FFFFFF"><div align="center">1</div></td>
					            <td width="7%"  height="5" valign="middle" bgcolor="#FFFFFF"><div align="center">2</div></td>
					            <td width="12%"  height="5" valign="middle" bgcolor="#FFFFFF"><div align="center">3</div></td>
					            <td width="12%"  height="5" valign="middle" bgcolor="#FFFFFF"><div align="center">4</div></td>
					            <td width="12%"  height="5" valign="middle" bgcolor="#FFFFFF"><div align="center">5 (3x4)</div></td>
					            <td width="12%"  height="5" valign="middle" bgcolor="#FFFFFF"><div align="center">6</div></td>
					          </tr>
					          <tr>
					            <td height="10" colspan="7" valign="middle" bgcolor="#FFFFFF"></td>
					          </tr>';
				$i=1;			  
				foreach($data['bill']['articole'] as $k=>&$v){	          
					$content.= '<tr>
					            <td width="3%" height="5" valign="middle" bgcolor="#FFFFFF"><div align="center">'. $i .'</div></td>
					            <td width="42%"  height="5" valign="middle" bgcolor="#FFFFFF"><div align="left">'. $v['produs'][0]['nume'] .'</div></td>
					            <td width="7%"  height="5" valign="middle" bgcolor="#FFFFFF"><div align="center">'. $v['produs'][0]['um'] .'</div></td>
					            <td width="12%"  height="5" valign="middle" bgcolor="#FFFFFF"><div align="center">'. $v['cantitate'] .'</div></td>
					            <td width="12%"  height="5" valign="middle" bgcolor="#FFFFFF"><div align="center" style="width:100%;">'. $v['pret_unitar'] .'</div></td>
					            <td width="12%"  height="5" valign="middle" bgcolor="#FFFFFF"><div align="center">'. $v['valoare'] .'</div></td>
					            <td width="12%"  height="5" valign="middle" bgcolor="#FFFFFF"><div align="center">'. $v['tva'] .'</div></td>
					          </tr>';
				$i++;
				}
			
					$content.= '<tr>
					            <td height="250" colspan="7" valign="top" bgcolor="#FFFFFF">
								<div id="detalii">';
					
					if(isset($data['bill']['detalii']) && !empty($data['bill']['detalii'])){			
					$content.='<table width="100%" border="0" cellspacing="0" cellpadding="0" style="margin-top:20px; font-size:11px;">
					              		<tr height="15">
					                		<td><div align="left">Detalii: '. $data['bill']['detalii'] .'</div></td>
					              		</tr>
					            	</table>';
					}	
					
					if(isset($data['bill']['nr_contract']) && !empty($data['bill']['nr_contract'])){				
					$content.='<table width="100%" border="0" cellspacing="0" cellpadding="0" style="margin-top:2px; font-size:11px;">
					                	<tr height="15">
					                  		<td><div align="left">Numar contract: '. $data['bill']['nr_contract'] .'</div></td>
					                	</tr>
					              	</table>';
					}
					$content.='</div>         
								  </td>
					          </tr>
					          <tr>
					            <td height="6" colspan="4" rowspan="3" valign="top" bgcolor="#FFFFFF">
								<div style="position:relative; top:-20px; clear:both">Intocmit de '. $data['bill']['FK_UTILIZATORI']['utilizator_nume'] .', CNP: '. $data['bill']['FK_UTILIZATORI']['utilizator_cnp'] .'</div>
						            <table width="100%" border="0" cellspacing="0" cellpadding="0" id="expeditie">
						              <tr>
						                <td width="30%">
										<div style="width:100%; margin-bottom:5px; font-size:11px;">Semnatura si stampila furnizorului,</div>
										<div style="height:130px; width:100%; border-right:1px solid #000;">
										';			
					if($data['bill']['stampila'] == 'DA'){
					$content.='<img src="'. $data['bill']['compania'][0]['stampila'] .'" style="border:none;">';	
					}
										
					$content.=		   '</div></td>
						                <td width="70%" valign="top">
											<table width="100%" border="0" cellpadding="0" cellspacing="0" id="expeditieDescriere">
									              <tr>
									                <td height="10"><div align="left"><span class="textBold">Date privind expeditia:</span></div></td>
									              </tr>
									              <tr>
									                <td height="10"><div align="left" class="borderDotted">Numele delegatului: '. $data['bill']['delegat'] .'</div></td>
									              </tr>
									              <tr>
									                <td height="10"><div align="left" class="borderDotted">BI/CI: '. $data['bill']['delegat_ci'] .'</div></td>
									              </tr>												  
									              <tr>
									                <td height="10"><div align="left" class="borderDotted">Mijlocul de transport '.  $data['bill']['mijloc_transport'] .' nr. '. $data['bill']['nr_auto'] .' </div></td>
									              </tr>
									              <tr>
									                <td height="10"><div align="left" class="borderDotted">Expedierea s-a facut in prezenta noastra la data de: </div></td>
									              </tr>
									              <tr>
									                <td height="10"><div align="left" class="borderDotted">'. DateConvertFromMySql($data['bill']['data_emiterii'],'d-m-Y') .'</div></td>
									              </tr>
									           </table>                
						                </td>
						              </tr>
						            </table>
								</td>
					            <td rowspan="2" valign="top" bgcolor="#FFFFFF"><div align="left" style="padding-left:5px;">Total din care accize: </div></td>
					            <td height="20" valign="top" bgcolor="#FFFFFF"><div align="center" class="textBold">'. $data['bill']['TOTAL_VAL'] .'</div></td>
					            <td height="20" valign="top" bgcolor="#FFFFFF"><div align="center" class="textBold">'. $data['bill']['TOTAL_TVA'] .'</div>
					            </td>
					          </tr>
					          <tr>
					            <td height="20" valign="top" bgcolor="#FFFFFF">&nbsp;</td>
					            <td height="20" valign="top" bgcolor="#FFFFFF"><div align="center">X</div></td>
					          </tr>
					          <tr>
					            <td height="70" valign="top" bgcolor="#FFFFFF"><div align="left" style="padding-left:5px;">Semnatura de primire</div></td>
					            <td height="70" colspan="2" valign="top" bgcolor="#FFFFFF"><div align="left">Total de plat&#259;:<br />(col.5 + col.6)</div>
					              <div align="center" class="textBold">
					                <div align="right" style="padding-right:30pt">'. $data['bill']['TOTAL'] .'</div>
					                <div align="right">'. $data['bill']['moneda'] .'</div>
					              </div></td>
					          </tr>
					        </table></td>
					      </tr>
					    </table></td>
					  </tr>
					</table>	
				';
				$footer = '
				</body>
				</html>
				';		
				echo $header.$content.$footer;			
				
				//--------------------------
				break;	
				
		} //end switch
	} //end function	
		
	function clearTempDataPDF(){
			delete_files("./tmp/pdf/");
	}	
	function clearTempDataXLS(){
			delete_files("./tmp/xls/");
	}	
}
?>
